import { useMemo } from 'react'
import dayjs from 'dayjs'
import { ColGroupDef } from '@ag-grid-community/core'

import { getLogisticsStatusName, getShipFromName } from '@oBiz/TrackOrder/utils'
import { TCol } from '../interface'
import { Cell } from './Cell'
import { getColExtFlags, getColHideFlags } from './utils'
import styles from './styles.module.less'

const YMDFormat = (v: string | null | undefined) => (v ? dayjs(v).$formatSmart($F_YMD) : '')

const YMDRangeFormat = (v1: string | null | undefined, v2: string | null | undefined) => {
  return ((v1 || v2) && [v1, v2].map(v => (v ? dayjs(v).$formatSmart($F_YMD) : '')).join(' ~ ')) || ''
}

export const useColDefs = () => {
  const colHideFlags = useMemo(() => getColHideFlags(), [])
  const colExtFlags = useMemo(() => getColExtFlags(), [])

  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      width: 180,
      sortable: false,
      toolPanelClass: styles.toolPanel,
      cellRenderer: Cell,
    }),
    [],
  )

  const columnDefs = useMemo(
    () => [
      {
        field: 'waybillNo',
        headerName: '运单号',
        width: 130,
      } satisfies TCol<'waybillNo'>,
      {
        field: '标签',
        width: 86,
      } satisfies TCol<'标签'>,
      {
        headerName: '日期',
        toolPanelClass: styles.toolPanel,
        groupId: '日期',
        openByDefault: !!colExtFlags['日期'],
        children: [
          {
            field: 'age',
            headerName: 'AGE',
            // lockVisible: true,
            width: 86,
          } satisfies TCol<'age'>,
          {
            field: 'deliveryDate',
            headerName: '发货日期',
            columnGroupShow: 'open',
            width: 114,
            valueFormatter: ({ value }) => YMDFormat(value),
          } satisfies TCol<'deliveryDate'>,
          {
            field: 'etd',
            headerName: 'ETD',
            columnGroupShow: 'open',
            width: 114,
            valueFormatter: ({ value }) => YMDFormat(value),
          } satisfies TCol<'etd'>,
          {
            field: 'eta',
            headerName: 'ETA',
            columnGroupShow: 'open',
            width: 114,
            valueFormatter: ({ value }) => YMDFormat(value),
          } satisfies TCol<'eta'>,
          {
            field: 'predictSigningTime',
            headerName: '预计签收日期',
            columnGroupShow: 'open',
            width: 142,
            valueFormatter: ({ value }) => YMDFormat(value),
          } satisfies TCol<'predictSigningTime'>,
          {
            field: 'practicalSigningTime',
            headerName: '实际签收日期',
            columnGroupShow: 'open',
            width: 142,
            valueFormatter: ({ value }) => YMDFormat(value),
          } satisfies TCol<'practicalSigningTime'>,
        ],
      } satisfies ColGroupDef,
      {
        headerName: '渠道',
        toolPanelClass: styles.toolPanel,
        groupId: '渠道',
        openByDefault: !!colExtFlags['渠道'],
        children: [
          {
            field: 'merchantServers',
            headerName: '服务商',
            // lockVisible: true,
          } satisfies TCol<'merchantServers'>,
          {
            field: 'logisticsChannel',
            headerName: '物流渠道',
            columnGroupShow: 'open',
            width: 210,
          } satisfies TCol<'logisticsChannel'>,
          {
            field: 'channelNo',
            headerName: '渠道单号',
            columnGroupShow: 'open',
          } satisfies TCol<'channelNo'>,
          {
            field: 'carrier',
            headerName: 'Carrier',
            columnGroupShow: 'open',
          } satisfies TCol<'carrier'>,
          {
            field: 'transferCodes',
            headerName: '转单号',
            columnGroupShow: 'open',
            width: 210,
            valueFormatter: ({ value }) => value?.join('、') || '',
          } satisfies TCol<'transferCodes'>,
          {
            field: 'shipName',
            headerName: '船名',
            columnGroupShow: 'open',
          } satisfies TCol<'shipName'>,
          {
            field: 'voyageNumber',
            headerName: '航次',
            columnGroupShow: 'open',
          } satisfies TCol<'voyageNumber'>,
          {
            field: 'containerNumber',
            headerName: '柜号',
            columnGroupShow: 'open',
          } satisfies TCol<'containerNumber'>,
          {
            field: 'flightNumber',
            headerName: '航班号',
            columnGroupShow: 'open',
          } satisfies TCol<'flightNumber'>,
        ],
      } satisfies ColGroupDef,
      {
        field: 'logisticsStatus',
        headerName: '物流状态',
        width: 114,
        valueFormatter: ({ value }) => getLogisticsStatusName(value) || '',
      } satisfies TCol<'logisticsStatus'>,
      {
        field: 'latestRoute',
        headerName: '最新路由',
        width: 210,
      } satisfies TCol<'latestRoute'>,
      {
        field: 'logisticsStatusEn',
        headerName: 'Status',
        width: 114,
      } satisfies TCol<'logisticsStatusEn'>,
      {
        field: 'latestRouteEn',
        headerName: 'Last Event',
        width: 210,
      } satisfies TCol<'latestRouteEn'>,
      {
        headerName: '地址',
        toolPanelClass: styles.toolPanel,
        groupId: '地址',
        openByDefault: !!colExtFlags['地址'],
        children: [
          {
            field: 'destination',
            headerName: '目的地',
            // lockVisible: true,
            width: 210,
          } satisfies TCol<'destination'>,
          {
            field: 'origin',
            headerName: '始发地',
            columnGroupShow: 'open',
            width: 210,
          } satisfies TCol<'origin'>,
          {
            field: 'originPort',
            headerName: '起运港',
            columnGroupShow: 'open',
            width: 210,
          } satisfies TCol<'originPort'>,
          {
            field: 'originAirport',
            headerName: '起运机场',
            columnGroupShow: 'open',
            width: 210,
          } satisfies TCol<'originAirport'>,
          {
            field: 'destinationAirport',
            headerName: '目的机场',
            columnGroupShow: 'open',
            width: 210,
          } satisfies TCol<'destinationAirport'>,
          {
            field: 'countryId',
            headerName: '国家',
            columnGroupShow: 'open',
          } satisfies TCol<'countryId'>,
        ],
      } satisfies ColGroupDef,
      {
        field: 'customer',
        headerName: '客户',
        width: 210,
      } satisfies TCol<'customer'>,
      {
        field: 'staffInfoList',
        headerName: '人员',
        cellStyle: { paddingTop: 4, paddingBottom: 4 }, // 头像占得多
        width: 210,
        valueFormatter: ({ value }) => value?.map(d => d.user.name).join('、') || '',
      } satisfies TCol<'staffInfoList'>,
      {
        headerName: '亚马逊',
        toolPanelClass: styles.toolPanel,
        groupId: '亚马逊',
        openByDefault: !!colExtFlags['亚马逊'],
        children: [
          {
            field: 'fbaId',
            headerName: 'FBAID',
            // lockVisible: true,
          } satisfies TCol<'fbaId'>,
          {
            field: 'reId',
            headerName: 'REID',
            columnGroupShow: 'open',
          } satisfies TCol<'reId'>,
          {
            field: 'predictTimeStart',
            headerName: 'DW(预计)',
            columnGroupShow: 'open',
            width: 194,
            valueFormatter: ({ data: d }) => YMDRangeFormat(d?.predictTimeStart, d?.predictTimeEnd),
          } satisfies TCol<'predictTimeStart'>,
          {
            field: 'practicalDeliveryTimeStart',
            headerName: 'DW(实际)',
            columnGroupShow: 'open',
            width: 194,
            valueFormatter: ({ data: d }) => YMDRangeFormat(d?.practicalDeliveryTimeStart, d?.practicalDeliveryTimeEnd),
          } satisfies TCol<'practicalDeliveryTimeStart'>,
          {
            field: 'shipFrom',
            headerName: 'Ship From',
            columnGroupShow: 'open',
            width: 123,
            valueFormatter: ({ value }) => getShipFromName(value) || '',
          } satisfies TCol<'shipFrom'>,
        ],
      } satisfies ColGroupDef,
      {
        headerName: '产品',
        toolPanelClass: styles.toolPanel,
        groupId: '产品',
        openByDefault: !!colExtFlags['产品'],
        children: [
          {
            field: 'boxes',
            headerName: '品名',
            // lockVisible: true,
            width: 210,
            valueFormatter: () => '',
          } satisfies TCol<'boxes'>,
          {
            field: '$boxNum',
            headerName: '箱数',
            columnGroupShow: 'open',
            width: 86,
          } satisfies TCol<'$boxNum'>,
        ],
      } satisfies ColGroupDef,
      {
        field: 'recordId',
        headerName: '操作',
        width: 150,
        pinned: 'right',
      } satisfies TCol<'recordId'>,
    ],
    [colExtFlags],
  )

  // 直接改写 columnDefs
  columnDefs.forEach((col: any) => {
    if ('children' in col) {
      col.children = col.children.map((c: any) => ({
        ...c,
        initialHide: !!colHideFlags[(c as TCol).field],
      }))
    } else {
      col.initialHide = !!colHideFlags[col.field]
    }
  })

  return { defaultColDef, columnDefs }
}
